package com.quanyan.club.web;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.quanyan.BaseRequest;
import com.quanyan.activity.response.RespActivityPoster;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.constants.ClubRedisConstants;
import com.quanyan.club.entity.RespClubMember;
import com.quanyan.club.entity.vo.req.*;
import com.quanyan.club.entity.vo.resp.*;
import com.quanyan.club.service.*;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.ServletUtils;
import com.quanyan.common.validation.base.Query;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Hugo.Wwg
 * @Since 2016-06-01
 */
@RestController
@RequestMapping(value = "/api/club/activity")
public class ClubActivityController extends BaseController {

    private static Logger logger = Logger.getLogger(ClubActivityController.class);

    @Autowired
    private ClubActivityService clubActivityService;
    @Autowired
    private ClubOpenService clubOpenService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private ActivityCRUDService activityCRUDService;
    @Autowired
    private ActivityAccountService activityAccountService;

    private static final String STATIC_HTML_URL = "club";

    /**
     * 俱乐部活动预支付下单
     */
    @RequestMapping(value = "/activityPrePaymentOrder", method = RequestMethod.POST)
    public APIResponse<ResPrePaymentOrderInfo> activityPrePaymentOrder(@RequestBody ReqSignUpInfo reqSignUpInfo,
                                                                       HttpServletRequest request) {
        Integer currentUserId = (Integer) request.getAttribute("uid");
        return clubActivityService.activityPrePaymentOrder(reqSignUpInfo, currentUserId, request);
    }

    /**
     * 俱乐部活动报名
     */
    @RequestMapping(value = "/userSignUp", method = RequestMethod.POST)
    public APIResponse<RespPreOrder> activitySignUp(@RequestBody ReqSignUpDetail reqSignUpInfo,
                                                    HttpServletRequest request) {
        Integer uid = (Integer) request.getAttribute("uid");
        if (uid == null) {
            return APIResponse.returnFail("用户没有登录");
        }
        String appVersion = (String) request.getAttribute("appVersion");
        String requestIp = ServletUtils.getClientIpAddress(request);

        String cancelKey = ClubRedisConstants.CLUB_CANCEL_ACTIVITY + reqSignUpInfo.getActivityId();
        RedisKey cancelRedisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, cancelKey);
        logger.warn("取消活动redisKey：" + cancelRedisKey);
        if (redisTemplate.exists(cancelRedisKey)) {
            return APIResponse.returnFail("该活动正在取消中");
        }
        String key = ClubRedisConstants.CLUB_SIGN_UP + reqSignUpInfo.getActivityId() + ":" + uid;
        RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
        if (redisTemplate.exists(redisKey)) {
            return APIResponse.returnFail("已经在报名了");
        } else {
            redisTemplate.set(redisKey, 1);
        }
        APIResponse response = null;
        try{
            response = clubActivityService.activitySignUp(
                    reqSignUpInfo, uid, requestIp, appVersion, request);
            logger.warn("resp" + JSONObject.toJSONString(response));
        }catch (Exception e)
        {
            redisTemplate.delteKey(redisKey);
            logger.warn(e.getMessage());
            if(e instanceof BizException)
            {
                return APIResponse.returnFail(e.getMessage());
            }
        }
        redisTemplate.delteKey(redisKey);
        return response;
    }

    /**
     * 继续支付(下单后没有立马支付的情况)
     */
    @RequestMapping(value = "/continuePayActivityOrder", method = RequestMethod.POST)
    public APIResponse<RespPreOrder> continuePayActivityOrder(
            HttpServletRequest request, @RequestBody ReqClubContinuePayOrder
            reqClubContinuePayOrder) {
        Integer uid = (Integer) request.getAttribute("uid");
        if (uid == null) {
            return APIResponse.returnFail("用户没有登录");
        }
        String appVersion = (String) request.getAttribute("appVersion");
        String businessOrderNo = reqClubContinuePayOrder.getBusinessOrderNo();
        Integer payId = reqClubContinuePayOrder.getPayId();
        String requestIp = ServletUtils.getClientIpAddress(request);
        if (Strings.isNullOrEmpty(businessOrderNo) || payId == null) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        reqClubContinuePayOrder.setRequestIp(requestIp);
        reqClubContinuePayOrder.setUid(uid);
        return clubActivityService.continuePayActivityOrder(
                reqClubContinuePayOrder, appVersion, request);
    }

    /**
     * 俱乐部活动订单详情
     */
    @RequestMapping(value = "/activityOrderDetail", method = RequestMethod.POST)
    public String activityOrderDetail(
            @RequestBody Map<String, Object> map,
            HttpServletRequest request) {

        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return JSONObject.toJSONString(APIResponse.returnFail("用户没有登录"));
        }

        Integer activityId = MapUtils.getInteger(map, "activityId");
        String businessOrderNo = MapUtils.getString(map, "businessOrderNo");
        if (activityId == null || activityId <= 0 || Strings.isNullOrEmpty(businessOrderNo)) {
            return JSONObject.toJSONString(APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY));
        }
        APIResponse response = clubActivityService.activityOrderDetail(activityId, userId, businessOrderNo);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 我的活动(订单列表)
     */
    @RequestMapping(value = "/activityOrderList", method = RequestMethod.POST)
    public String activityOrderList(
            @RequestBody Map<String, Object> map,
            HttpServletRequest request) {

        Integer uid = (Integer) request.getAttribute("uid");
        if (uid == null) {
            return JSONObject.toJSONString(APIResponse.returnFail("用户没有登录"));
        }
        Integer pageNum = MapUtils.getInteger(map, "pageNum");
        Integer pageSize = MapUtils.getInteger(map, "pageSize");

        if (pageNum == null || pageNum <= 0 ) {
            pageNum = 1;
        } else {
            ++pageNum;
        }

        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }

        APIResponse response = clubActivityService.activityOrderList(uid, pageNum, pageSize);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 取消未支付订单
     */
    @RequestMapping(value = "/cancelNotPayActivityOrder", method = RequestMethod.POST)
    public APIResponse cancelNotPayActivityOrder(
            @RequestBody Map<String, Object> map,
            HttpServletRequest request) {

        Integer uid = (Integer) request.getAttribute("uid");
        if (uid == null) {
            return APIResponse.returnFail("用户没有登录");
        }

        Integer activityId = MapUtils.getInteger(map, "activityId");
        String businessOrderNo = MapUtils.getString(map, "businessOrderNo");

        if (activityId == null || activityId <= 0 || Strings.isNullOrEmpty(businessOrderNo)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        String key = ClubRedisConstants.CLUB_CANCEL_NOT_PAY + businessOrderNo;
        RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
        APIResponse response = null;
        if (redisTemplate.exists(redisKey)) {
            return APIResponse.returnFail("该订单正在取消中");
        } else {
            redisTemplate.set(redisKey, 1);
        }
        try{
            response = clubActivityService.cancelNotPayActivityOrder(uid, activityId, businessOrderNo);
        }catch (Exception e){
            redisTemplate.delteKey(redisKey);
            logger.warn(e.getMessage());
            throw new BizException(e.getMessage());
        }
        redisTemplate.delteKey(redisKey);
        return response;
    }

    /**
     * 俱乐部活动评价
     */
    @RequestMapping(value = "/activityAppraise", method = RequestMethod.POST)
    public APIResponse<ResActivityOrderDetail> activityAppraise(
            @RequestBody Map<String, Object> map,
            HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return APIResponse.returnFail("用户没有登录");
        }

        Integer activityId = MapUtils.getInteger(map, "activityId");
        if (activityId == null || activityId <= 0) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }

        String businessOrderNo = MapUtils.getString(map, "businessOrderNo");
        if (Strings.isNullOrEmpty(businessOrderNo)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }

        Integer score = MapUtils.getInteger(map, "score");
        String content = MapUtils.getString(map, "content", "");
        //APP3.0 评价晒图功能
        List<String> lstPics = null;
        if(map.containsKey("lstPic"))
        {
            lstPics = (List<String>)map.get("lstPic");
        }
        return clubActivityService.activityAppraise(userId, activityId,
                score, content, businessOrderNo, lstPics);
    }

    /**
     * 俱乐部活动评价2.5
     */
    @RequestMapping(value = "/activityAppraiseNew", method = RequestMethod.POST)
    public String activityAppraise(
            @RequestBody @Valid ReqActivityComment reqActivityComment,
            HttpServletRequest request, BindingResult bindingResult) {
        Integer userId = getUid(request, true);
        APIResponse apiResponse = activityCRUDService.activityAppraise(userId, reqActivityComment);
        return JSONObject.toJSONString(apiResponse,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    @RequestMapping(value = "/appraiseSetting", method = RequestMethod.POST)
    public String appraiseSetting(
            @RequestBody BaseRequest baseRequest,
            HttpServletRequest request) {
        int userId = getUid(request, true);
        APIResponse apiResponse = activityCRUDService.getAppraiseSetting();
        return JSONObject.toJSONString(apiResponse,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 创建俱乐部活动
     */
    @RequestMapping(value = "/createActivity", method = RequestMethod.POST)
    public String createActivity(@RequestBody @Valid ReqClubActivity reqClubActivity,
                                 BindingResult bindingResult,
                                 HttpServletRequest request) {
        //权限检查
        int uid = getUid(request, true);
        reqClubActivity.setUid(uid);
        if (null == reqClubActivity.getActivityId()) {
            reqClubActivity.setActivityId(reqClubActivity.getId());
        }
        if(!clubMemberService.isClubAdminMember(uid, reqClubActivity.getClubId()))
        {
            return JSONObject.toJSONString(
                    APIResponse.returnFail("请先加入俱乐部并努力获取管理员权限。"));
        }
        APIResponse response = activityCRUDService.saveActivity(reqClubActivity);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 编辑俱乐部活动
     */
    @RequestMapping(value = "/updateActivity", method = RequestMethod.POST)
    public String updateActivity(@RequestBody ReqClubActivity reqClubActivity,
                                 BindingResult bindingResult,
                                 HttpServletRequest request) {
        int uid = getUid(request, true);
        if(!clubMemberService.isClubAdminMember(uid, reqClubActivity.getClubId()))
        {
            return JSONObject.toJSONString(
                    APIResponse.returnFail("请先加入俱乐部并努力获取管理员权限。"));
        }
        if (null == reqClubActivity.getActivityId()) {
            reqClubActivity.setActivityId(reqClubActivity.getId());
        }
        APIResponse response = activityCRUDService.updateActivity(reqClubActivity);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 暂停活动
     * @param reqSuspendInfo
     * @param request
     * @return
     */
    @RequestMapping(value = "/suspendActivity", method = RequestMethod.POST)
    public APIResponse suspendActivity(@RequestBody ReqSuspendInfo reqSuspendInfo, HttpServletRequest request) {
        Integer uid = (Integer) request.getAttribute("uid");
        if (uid == null) {
            return APIResponse.returnFail(ApiResponseEnum.NEED_USER_LOGIN.getId(), "用户没有登录");
        }
        reqSuspendInfo.setUid(uid);
        return activityCRUDService.suspendActivity(reqSuspendInfo);
    }

    /**
     * 恢复暂停活动
     * @param reqSuspendInfo
     * @param request
     * @return
     */
    @RequestMapping(value = "/reSuspendActivity", method = RequestMethod.POST)
    public APIResponse reSuspendActivity(@RequestBody ReqSuspendInfo reqSuspendInfo, HttpServletRequest request) {
        Integer uid = (Integer) request.getAttribute("uid");
        if (uid == null) {
            return APIResponse.returnFail("用户没有登录");
        }
        reqSuspendInfo.setUid(uid);
        return activityCRUDService.reSuspendActivity(reqSuspendInfo);
    }


    /**
     * 管理员取消俱乐部活动
     */
    @RequestMapping(value = "/cancelActivity", method = RequestMethod.POST)
    public APIResponse cancelActivity(@RequestBody ReqClubActivityOperate reqClubActivityOperate, HttpServletRequest request) {
        int uid = getUid(request, true);
        String key = ClubRedisConstants.CLUB_CANCEL_ACTIVITY + reqClubActivityOperate.getActivityId();
        int larkAppId = reqClubActivityOperate.getLarkAppId();
        RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
        APIResponse response = null;
        if (redisTemplate.exists(redisKey)) {
            return APIResponse.returnFail("该活动正在取消中");
        } else {
            redisTemplate.set(redisKey, 1);
        }
        try{
            response = clubActivityService.cancelActivity(reqClubActivityOperate.getActivityId(),
                    uid, false,larkAppId);
        }catch (Exception e){
            redisTemplate.delteKey(redisKey);
            logger.warn(e.getMessage());
            throw new BizException(e.getMessage());
        }
        redisTemplate.delteKey(redisKey);
        return response;
    }

    /**
     * 用户取消俱乐部活动订单
     */
    @RequestMapping(value = "/cancelActivityOrder", method = RequestMethod.POST)
    public APIResponse cancelActivityOrder(@RequestBody Map<String, String> map, HttpServletRequest request) {
        if (!map.containsKey("businessOrderNo")) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        int uid = getUid(request, true);
        String businessOrderNo = (String) map.get("businessOrderNo");
        String key = ClubRedisConstants.CLUB_CANCEL_PAY + businessOrderNo;
        RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
        APIResponse response = null;
        if (redisTemplate.exists(redisKey)) {
            return APIResponse.returnFail("该订单正在取消中");
        } else {
            redisTemplate.set(redisKey, 1);
        }
        try{
            response = clubActivityService.cancelOrderNotify(uid, businessOrderNo, 1, "用户主动取消");
        }catch (Exception e){
            redisTemplate.delteKey(redisKey);
            logger.warn(e.getMessage());
            throw new BizException(e.getMessage());
        }
        redisTemplate.delteKey(redisKey);
        return response;
    }

    /**
     * 获取活动详情
     */
    @RequestMapping(value = "/activityDetail", method = RequestMethod.POST)
    public String activityDetail(@RequestBody ReqClubActivityOperate reqClubActivityOperate, HttpServletRequest request) {
        Integer uid = null;
        if (null != request.getAttribute("uid")) {
            uid = (Integer) request.getAttribute("uid");
        }
        Integer activityId = reqClubActivityOperate.getActivityId();
        if (null == activityId || activityId == 0) {
            return JSONObject.toJSONString(
                    APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY));
        }
        APIResponse response = activityCRUDService.queryClubActivityById(reqClubActivityOperate.getActivityId(), uid);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 获取活动详情（管理）
     */
        @RequestMapping(value = "/activityDetailAdmin", method = RequestMethod.POST)
    public String activityDetailAdmin(@RequestBody ReqClubActivityOperate reqClubActivityOperate, HttpServletRequest request) {
        Integer uid = getUid(request, true);
        APIResponse response = activityCRUDService.queryClubActivityByAdmin(reqClubActivityOperate.getActivityId(), uid);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 活动成员列表
     */
    @RequestMapping(value = "/activityMemberList", method = RequestMethod.POST)
    public String activityMemberList(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        Integer activityId = MapUtils.getInteger(map, "activityId");
        if (StringUtils.isEmpty(activityId)) {
            return JSONObject.toJSONString(APIResponse.returnFail("activityId is null"));
        }
        Integer uid = null;
        if (null != request.getAttribute("uid")) {
            uid = (Integer) request.getAttribute("uid");
        }
        APIResponse response = activityAccountService.getActivityMemberList(activityId, uid);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 活动成员列表(IM)
     */
    @RequestMapping(value = "/activityMemberListIM", method = RequestMethod.POST)
    public String activityMemberListNew(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        Integer activityId = MapUtils.getInteger(map, "activityId");;
        if (StringUtils.isEmpty(activityId)) {
            return JSONObject.toJSONString(APIResponse.returnFail("activityId is null"));
        }
        Integer uid = null;
        if (null != request.getAttribute("uid")) {
            uid = (Integer) request.getAttribute("uid");
        }
        APIResponse response = activityAccountService.getActivityMemberListIM(activityId, uid);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 活动列表
     */
    @RequestMapping(value = "/activityList", method = RequestMethod.POST)
    public String activityList(@RequestBody ReqClubActivitySearch reqClubActivitySearch, HttpServletRequest request) {
        Integer uid = (Integer)request.getAttribute("uid");
        reqClubActivitySearch.setCurrentUserId(uid);
        APIResponse response = clubActivityService.queryActivityListByCondition(reqClubActivitySearch);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }


    /**
     * 活动列表，与我相关的活动列表，包括创建的，管理的，加入的。
     */
    @RequestMapping(value = "/myDetailActivityList", method = RequestMethod.POST)
    public String MyDetailActivityList(@RequestBody ReqClubActivitySearch reqClubActivitySearch, HttpServletRequest request) {
        Integer uid = (Integer) request.getAttribute("uid");
        APIResponse response = clubActivityService.queryMyDetailActivityListByCondition(reqClubActivitySearch, uid);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 俱乐部活动查询列表(管理)
     */
    @RequestMapping(value = "/QueryClubActivityList", method = RequestMethod.POST)
    public String queryClubActivityList(@RequestBody @Valid ReqClubActivityCondition req,
                                   HttpServletRequest request,
                                   BindingResult bindingResult) {
        Integer userId = (Integer) request.getAttribute("uid");
        PageObj<List<RespClubActivity>> pageObj =
                activityCRUDService.clubActivityListByCriteria(req, userId);
        if (null == pageObj) {
            return JSONObject.toJSONString(APIResponse.returnFail("没有活动"));
        }
        return JSONObject.toJSONString(APIResponse.returnSuccess(pageObj),
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 所有俱乐部活动查询列表（C端3.0）
     */
    @RequestMapping(value = "/myClubActivityList", method = RequestMethod.POST)
    public String queryMyClubActivityList(@RequestBody @Valid ReqClubActivityCondition req,
                                        HttpServletRequest request,
                                        BindingResult bindingResult) {
        Integer userId = getUid(request, true);
        PageObj<List<RespClubActivity>> pageObj =
                activityCRUDService.clubActivityListByCriteria(req, userId);
        if (null == pageObj) {
            return JSONObject.toJSONString(APIResponse.returnFail("没有活动"));
        }
        return JSONObject.toJSONString(APIResponse.returnSuccess(pageObj),
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 俱乐部活动列表
     */
    @RequestMapping(value = "/clubActivityList", method = RequestMethod.POST)
    public String clubActivityList(@RequestBody @Valid ReqClubActivityCondition req,
                                   HttpServletRequest request,
                                   BindingResult bindingResult) {
        Integer userId = (Integer) request.getAttribute("uid");
        PageObj<List<RespClubActivity>> pageObj =
                activityCRUDService.clubActivityListByCriteria(req, userId);
        if (null == pageObj) {
            return JSONObject.toJSONString(APIResponse.returnFail("没有活动"));
        }
        return JSONObject.toJSONString(APIResponse.returnSuccess(pageObj),
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 收藏/取消收藏活动
     */
    @RequestMapping(value = "/collectActivity", method = RequestMethod.POST)
    public String collectActivity(@RequestBody ReqClubActivityOperate reqClubActivityOperate, HttpServletRequest request) {
        int uid = getUid(request, true);
        Integer activityId = reqClubActivityOperate.getActivityId();
        Integer type = reqClubActivityOperate.getType();

        if (StringUtils.isEmpty(activityId)) {
            return JSONObject.toJSONString(APIResponse.returnFail("activityId is null"));
        }
        if (StringUtils.isEmpty(type)) {
            return JSONObject.toJSONString(APIResponse.returnFail("type is null"));
        }
        APIResponse response = clubActivityService.collect(uid, reqClubActivityOperate.getActivityId(), reqClubActivityOperate.getType());
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 收藏活动列表  页码从0开始
     */
    @RequestMapping(value = "/collectActivityList", method = RequestMethod.POST)
    public String collectActivityList(@RequestBody ReqClubActivitySearch reqClubActivitySearch, HttpServletRequest request) {
        int uid = getUid(request, true);
        Integer pageIndex = reqClubActivitySearch.getPageNum() + 1;
        Integer pageSize = reqClubActivitySearch.getPageSize();

        if (!StringUtils.isEmpty(uid)) {
            if (StringUtils.isEmpty(pageIndex)) {
                pageIndex = 1;
            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = Constants.DEFAULT_PAGE_SIZE;
            }
            APIResponse response = clubActivityService.queryActivityListCollect(uid, pageIndex, pageSize);
            return JSONObject.toJSONString(response,
                    SerializerFeature.WriteNullBooleanAsFalse,
                    SerializerFeature.WriteNullListAsEmpty,
                    SerializerFeature.WriteNullNumberAsZero,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteNullStringAsEmpty);
        } else {
            return JSONObject.toJSONString(APIResponse.returnFail("uid is null"));
        }
    }

    /*
     * 活动分享
     */
    @RequestMapping(value = "/activityShare", method = RequestMethod.POST)
    public String shareClubActivity(@RequestBody Map<String, Object> map, BindingResult bindingResult,
                                    HttpServletRequest request) {
        Integer uid = (Integer) request.getAttribute("uid");
        if (null == MapUtils.getInteger(map, "activityId")) {
            return JSONObject.toJSONString(APIResponse.returnFail("activityId can not be null"));
        }
        Integer activityId = MapUtils.getInteger(map, "activityId");
        APIResponse<RespShareActivity> result = clubActivityService.shareClubActivityById(activityId, request);
        if (null == result) {
            return JSONObject.toJSONString(APIResponse.returnFail("分享失败"));
        }
        return JSONObject.toJSONString(result,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 活动海报列表 页码从0开始
     */
    @RequestMapping(value = "/poster", method = RequestMethod.POST)
    public String selectActivityPosterList(@RequestBody @Valid ReqClubActivityPoster req, BindingResult bindingResult) {
        PageObj<List<RespActivityPoster>> pageObj =
                clubActivityService.selectActivityPosterList(req.getPageNum(),
                        req.getPageSize(), req.getCategoryId(), req.getClubId());
        if (null == pageObj) {
            return JSONObject.toJSONString(APIResponse.returnFail("没有活动海报"));
        }
        if(null == pageObj.getItems())
        {
            pageObj.setItems(new ArrayList<RespActivityPoster>());
        }
        return JSONObject.toJSONString(APIResponse.returnSuccess(pageObj),
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 批量增加活动海报列表
     */
    @RequestMapping(value = "/poster/add", method = RequestMethod.POST)
    public String addActivityPosterList(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        int uid = getUid(request, true);
        Integer categoryId = MapUtils.getInteger(map, "categoryId");
        Integer clubId = MapUtils.getInteger(map, "clubId");
        List<String> urls = (List<String>)map.get("urls");
        APIResponse response =
                clubActivityService.batchAddActivityPoster(urls, uid, categoryId, clubId);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 批量删除活动海报列表
     */
    @RequestMapping(value = "/poster/delete", method = RequestMethod.POST)
    public String deleteActivityPosterList(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        int uid = getUid(request, true);
        if (null == map.get("ids")) {
            return JSONObject.toJSONString(
                    APIResponse.returnFail("posters can not be null"));
        }
        List<Integer> posterIds = (List)map.get("ids");
        Integer clubId = MapUtils.getInteger(map, "clubId");
        if(null == clubId)
        {
            return JSONObject.toJSONString(
                    APIResponse.returnFail("clubId can not be null"));
        }
        APIResponse response =
                clubActivityService.batchDeleteActivityPoster(posterIds, clubId, uid);
        return JSONObject.toJSONString(response,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }

    /**
     * 补报名成员账户列表
     */
    @RequestMapping(value = "/clubMemberAccountList", method = RequestMethod.POST)
    public APIResponse<List<RespClubMember>> clubMemberAccountList(
            @RequestBody @Validated(Query.class)
                    ReqClubMemberAccount reqClubActivitySearch,
            BindingResult result,
            HttpServletRequest request) {

        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return APIResponse.returnFail("用户没有登录");
        }

        if (!clubMemberService.isClubAdminMember(userId, reqClubActivitySearch.getClubId())) {
            //判断权限(主席或者财务管理员)
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }

        return clubActivityService.clubMemberAccountList(userId, reqClubActivitySearch);
    }

    /**
     * 俱乐部活动补报名
     */
    @RequestMapping(value = "/memberManageMendSignUp", method = RequestMethod.POST)
    public APIResponse memberManageMendSignUp(
            @RequestBody @Validated(Query.class)
                    ReqClubActivityMendSignUp reqClubActivityMendSignUp,
            BindingResult result,
            HttpServletRequest request) {

        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return APIResponse.returnFail("用户没有登录");
        }

        if (!clubMemberService.isClubAdminMember(userId, reqClubActivityMendSignUp.getClubId())) {
            //判断权限(主席或者财务管理员)
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }

        return clubActivityService.memberManageMendSignUp(userId, reqClubActivityMendSignUp);
    }

    /**
     * 俱乐部现场管理
     */
    @RequestMapping(value = "/memberManageList", method = RequestMethod.POST)
    public APIResponse<Map<String, Object>> memberManageList(
            @RequestBody Map<String, Object> map,
            HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return APIResponse.returnFail("用户没有登录");
        }

        Integer activityId = MapUtils.getInteger(map, "activityId");
        Integer clubId = MapUtils.getInteger(map, "clubId");

        if (activityId == null || activityId <= 0 || clubId == null || clubId <= 0) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }

        if (!clubMemberService.isClubAdminMember(userId, clubId)) {
            //判断权限(主席或者财务管理员)
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }

        return clubActivityService.memberManageList(userId, activityId, clubId);
    }

    /**
     * 俱乐部现场管理提交
     */
    @RequestMapping(value = "/memberManagerSubmit", method = RequestMethod.POST)
    public APIResponse memberManagerSubmit(
            @RequestBody @Validated(Query.class)
                    List<ResClubActivityMemberManage> resClubActivityMemberManages,
            HttpServletRequest request) {

        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return APIResponse.returnFail("用户没有登录");
        }

        if (CollectionUtils.isEmpty(resClubActivityMemberManages)) {
            return APIResponse.returnFail("无变更操作");
        }

        if (!clubMemberService.isClubAdminMember(userId, resClubActivityMemberManages.get(0).getClubId())) {
            //判断权限(主席或者财务管理员)
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }

        return clubActivityService.memberManagerSubmit(userId, resClubActivityMemberManages);
    }

    /**
     * 俱乐部活动结算明细列表
     */
    @RequestMapping(value = "/settlementDetailList", method = RequestMethod.POST)
    public APIResponse<Map<String, Object>> settlementDetailList(
            @RequestBody @Validated(Query.class) ReqClubActivityInfo reqClubActivityInfo,
            HttpServletRequest request) {

        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return APIResponse.returnFail("用户没有登录");
        }

        if (!clubMemberService.isClubAdminMember(userId, reqClubActivityInfo.getClubId())) {
            //判断权限(主席或者财务管理员)
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }

        return clubActivityService.settlementDetailList(userId, reqClubActivityInfo);
    }

    private static Map<Integer,Integer> flagSettle = new HashMap<Integer,Integer>();
    /**
     * 俱乐部活动结算
     */
    @RequestMapping(value = "/activitySettlement", method = RequestMethod.POST)
    public APIResponse activitySettlement(
            @RequestBody Map<String, Object> map,
            HttpServletRequest request) {

        Integer userId = (Integer) request.getAttribute("uid");
        if (userId == null) {
            return APIResponse.returnFail("用户没有登录");
        }

        Integer activityId = MapUtils.getInteger(map, "activityId");
        Integer clubId = MapUtils.getInteger(map, "clubId");
        if (activityId == null || activityId <= 0 || clubId == null || clubId <= 0) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }

        if (!clubMemberService.isClubAdminMember(userId, clubId)) {
            //判断权限(主席或者财务管理员)
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }
        String key = ClubRedisConstants.CLUB_ACTIVITY_SETTLE + activityId;
        RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
        APIResponse response = null;
        if (redisTemplate.exists(redisKey)) {
            return APIResponse.returnFail("该活动正在结算中");
        } else {
            redisTemplate.set(redisKey, 1);
        }
        try{
            response = clubActivityService.activitySettlement(activityId, clubId, userId, false);
        }catch (Exception e){
            redisTemplate.delteKey(redisKey);
            logger.warn(e.getMessage());
            throw new BizException(e.getMessage());
        }
        redisTemplate.delteKey(redisKey);
        return response;
    }

    /**
     * 俱乐部活动结算
     */
    @RequestMapping(value = "/activityAfterWeek", method = RequestMethod.POST)
    public String queryClubActivityListAfterWeek(ReqClubActivityCondition reqClubActivityCondition)
    {
        reqClubActivityCondition.setPageNum(reqClubActivityCondition.getPageNum() + 1);
        PageObj pageObj =
                activityCRUDService.queryClubActivityListAfterWeek(reqClubActivityCondition);
        return JSONObject.toJSONString(APIResponse.returnSuccess(pageObj),
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
    }


    //**************************************以下为调试用，客户端不用**************************************
    //**************************************以下为调试用，客户端不用**************************************
    //**************************************以下为调试用，客户端不用**************************************
    //**************************************以下为调试用，客户端不用**************************************

    /**
     * 最新活动推荐
     */
    @RequestMapping(value = "/latestActivityInfo", method = RequestMethod.POST)
    public APIResponse latestActivityInfo(@RequestBody ReqClubActivityOperate reqClubActivityOperate, HttpServletRequest request) {

        return null;//APIResponse.returnSuccess(clubOpenService.latestActivityInfo(reqClubActivityOperate.getPlaceId(),  1));
    }
//

    /**
     * 批量查询活动列表
     */
    @RequestMapping(value = "/batchQueryActivityList", method = RequestMethod.POST)
    public APIResponse batchQueryActivityList(@RequestBody ReqClubActivityOperate reqClubActivityOperate, HttpServletRequest request) {
        return APIResponse.returnSuccess(clubOpenService.batchQueryActivityList(reqClubActivityOperate.getActivityIdList()));
    }
}
